<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>用户管理</title>
    <link rel="stylesheet" href="${ctxPath}/assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/formSelects/formSelects-v4.css"/>
</head>

<body>
<% include("../layout/loading.html"){} %>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <select id="sltKey">
                            <option value="">请选择搜索条件</option>
                            <option value="username">账号</option>
                            <option value="nick_name">用户名</option>
                            <option value="sex">性别</option>
                        </select>
                    </div>
                    <div class="layui-inline">
                        <input id="edtSearch" class="layui-input" type="text" placeholder="输入关键字"/>
                    </div>
                    <div class="layui-inline">
                        <button id="btnSearch" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
                        <button id="btnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
                    </div>
                </div>
            </div>

            <table class="layui-table" id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn  layui-btn-normal layui-btn-xs" lay-event="channel">渠道分配</a>
    <a class="layui-btn layui-btn-xs" lay-event="reset">重置密码</a>
    <a class="layui-btn layui-btn-xs" lay-event="clearLoginLimit">清除登录限制</a>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="tableState">
    <input type="checkbox" lay-filter="ckState" value="{{d.userId}}" lay-skin="switch"
           lay-text="正常|锁定" {{d.state==0?'checked':''}}/>
</script>
<!-- 表单弹窗 -->
<script type="text/html" id="modelUser">
    <form id="modelUserForm" lay-filter="modelUserForm" class="layui-form model-form">
        <input name="userId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
                <input name="username" placeholder="请输入账号" type="text" class="layui-input" maxlength="20"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input name="nickName" placeholder="请输入用户名" type="text" class="layui-input" maxlength="20"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="1" title="男" checked/>
                <input type="radio" name="sex" value="2" title="女"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="roleId" xm-select="roleId" lay-verType="tips" lay-verify="required">
                    <% for(role in roles) { %>
                    <option value="${role.roleId}">${role.roleName}</option>
                    <% } %>
                </select>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn" lay-filter="modelUserSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script type="text/javascript" src="${ctxPath}/assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="${ctxPath}/assets/js/common.js"></script>
<script>
    var treeData = [];
    layui.use(['layer', 'form', 'table', 'util', 'admin', 'formSelects', 'zTree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var admin = layui.admin;
        var formSelects = layui.formSelects;

        //性别字典
        var sexDatas = ${dict.getDictJson('user_sex')};

        // 渲染表格
        var insTb = table.render({
            elem: '#userTable',
            url: 'user/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'},
                {field: 'username', title: '账号'},
                {field: 'nickName', title: '用户名'},
                {field: 'sex', title: '性别', templet:function (d) {
                        return getDictName(sexDatas, d.sex);
                    }},
                {field: 'type', title: '类型',templet:function (d) {
                    if (d.type == 0){
                        return "甲方";
                    } else {
                        return "乙方";
                    }
                    }},
                {
                    field: 'roleName', title: '角色', templet: function (d) {
                        return d.roles.map(function (item) {
                            return '<span class="layui-badge layui-badge-gray">' + item.roleName + '</span>';
                        }).join('&nbsp;&nbsp;');
                    }, width: 150
                },
                {
                    templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, title: '创建时间'
                },
                {templet: '#tableState', title: '状态'},
                {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 360}
            ]],
            where:{
                type: 0,
            }
        });

        // 添加
        $('#btnAdd').click(function () {
            showEditModel();
        });

        // 搜索
        $('#btnSearch').click(function () {
            var key = $('#sltKey').val();
            var value = $('#edtSearch').val();
            if (value && !key) {
                layer.msg('请选择搜索条件', {icon: 2});
            }
            insTb.reload({where: {searchKey: key, searchValue: value}});
        });

        // 工具条点击事件
        table.on('tool(userTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (layEvent === 'del') { // 删除
                doDel(data.userId, data.nickName);
            } else if (layEvent === 'reset') { // 重置密码
                resetPsw(data.userId, data.nickName);
            } else if (layEvent === 'channel') {
                showChannelSelectModel(data);
            } else if (layEvent === 'clearLoginLimit'){
                $.post('user/clearLoginLimit', {
                    username: data.username
                }, function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            }
        });

        // 显示表单弹窗
        function showEditModel(mUser) {
            admin.open({
                type: 1,
                title: (mUser ? '修改' : '添加') + '用户',
                area: ['650px', '500px'],
                content: $('#modelUser').html(),
                success: function (layero, dIndex) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    var url = mUser ? 'user/update' : 'user/add';
                    // 回显数据
                    var roleIds = new Array();
                    var channelIds = new Array();
                    if (mUser) {
                        $('input[name="username"]').attr('readonly', 'readonly');
                        form.val('modelUserForm', mUser);
                        for (var i = 0; i < mUser.roles.length; i++) {
                            roleIds.push(mUser.roles[i].roleId);
                        }
                        if (mUser.channelId) {
                            channelIds = mUser.channelId.split(",");
                        }
                    } else {
                        form.render('radio');
                    }
                    formSelects.render('roleId', {init: roleIds});
                    formSelects.render('channelId', {init: channelIds});
                    // 表单提交事件
                    form.on('submit(modelUserSubmit)', function (data) {
                        data.field.roleIds = formSelects.value('roleId', 'valStr');
                        data.field.channelId = formSelects.value('channelId', 'valStr');
                        //甲方账号
                        data.field.type = 0;
                        layer.load(2);
                        $.post(url, data.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.close(dIndex);
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'json');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDel(userId, nickName) {
            top.layer.confirm('确定要删除“' + nickName + '”吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                top.layer.close(i);
                layer.load(2);
                $.post('user/delete', {
                    userId: userId
                }, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        insTb.reload();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            });
        }

        // 修改用户状态
        form.on('switch(ckState)', function (obj) {
            layer.load(2);
            $.post('user/updateState', {
                userId: obj.elem.value,
                state: obj.elem.checked ? 0 : 1
            }, function (res) {
                layer.closeAll('loading');
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 2});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'json');
        });

        // 重置密码
        function resetPsw(userId, nickName) {
            top.layer.confirm('确定要重置“' + nickName + '”的登录密码吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                top.layer.close(i);
                layer.load(2);
                $.post('user/restPsw', {
                    userId: userId
                }, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            });
        }

        //渠道
        function showChannelSelectModel(mUser) {
            admin.open({
                title: '用户所属渠道分配',
                btn: ['保存', '取消'],
                area: ['400px', '650px'],
                content: '<div id="channelSelect"></div><ul id="treeAuth" class="ztree"></ul>',
                success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css({'max-height': '650px', 'overflow': 'auto'});
                    layer.load(2);
                    var setting =  {check: {enable: true}, data: {simpleData: {enable: true}},view: {nameIsHTML: true}};
                    $.get('/cms/channel/channelTree', {
                        userId: mUser.userId
                    }, function (res) {
                        treeData = res;
                        $.fn.zTree.init($('#treeAuth'), setting, res);
                        var parentNodes = [];
                        for (let i = 0; i < res.length; i++) {
                            if (res[i].pId == 0){
                                parentNodes.push(res[i]);
                            }
                        }
                        var html = '<span style="margin-right: 20px">快速选择</span>' +
                            '<button class="layui-btn layui-btn-sm" onclick="checkChannel(0)" style="margin-right: 10px">全部</button>';
                        for (let i = 0; i < parentNodes.length; i++) {
                            html += '<button class="layui-btn layui-btn-sm" onclick="checkChannel(\''+parentNodes[i].id+'\')" style="margin-right: 10px">'+ parentNodes[i].name +'</button>';
                        }
                        $("#channelSelect").html(html);
                        layer.closeAll('loading');
                    }, 'json');
                },
                yes: function (index, layero) {
                    layer.load(2);
                    var treeObj = $.fn.zTree.getZTreeObj('treeAuth');
                    var nodes = treeObj.getCheckedNodes(true);
                    var ids = [];
                    for (let i = 0; i < nodes.length; i++) {
                        if(nodes[i].pId != null && nodes[i].pId != 0){
                            ids.push(nodes[i].id);
                        }
                    }
                    $.post('/cms/channel/updateUserChannel', {
                        userId: mUser.userId,
                        channelIds: JSON.stringify(ids)
                    }, function (res) {
                        layer.closeAll('loading');
                        if (200 == res.code) {
                            layer.msg(res.msg, {icon: 1});
                            layer.close(index);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'json');
                }
            });
        }
    });

    function checkChannel(groupId){
        var treeObj = $.fn.zTree.getZTreeObj('treeAuth');
        var nodes = treeObj.getCheckedNodes(true);
        if (groupId == 0){
            if(nodes.length != treeData.length){
                treeObj.checkAllNodes(true)
            }else {
                treeObj.checkAllNodes(false)
            }
            return;
        }
        var chooseNodes = treeObj.getNodesByParam("pId", groupId, null);
        var checkTimes = 0;
        for (let i = 0; i < chooseNodes.length; i++) {
            checkTimes += chooseNodes[i].checked;
        }
        if(checkTimes != chooseNodes.length){
            for (let i = 0; i < chooseNodes.length; i++) {
                treeObj.checkNode(chooseNodes[i], true, true);
            }
        }else {
            for (let i = 0; i < chooseNodes.length; i++) {
                treeObj.checkNode(chooseNodes[i], false, true);
            }
        }
    }
</script>

</body>
</html>